define([
  'views/View',
  'views/media/PhotoAlbumModal',
  'hbs!template/media/image-preview',
  'hbs!template/media/media-check'
], function(View, PhotoAlbumModal, template, check_template){
  var CheckView = View.extend({
    template: check_template,
    
    events: {
      "click div[name=minus]":  "selection",
      "click div[name=plus]":  "selection"      
    },

    initialize: function() {
      this.model.bind("change:selected", this.render, this);
    },

    render: function() {
      if(this.template) {
        console.log("Media file!");
        console.log(this.template(this.getRenderData()));
        $(this.el).html(this.template(this.getRenderData()));
      }
      return this;
    },

    selection: function() {
      console.log("Selection!!!");
      var selected = this.model.get('selected');
      this.model.set({selected: !selected});
      //this.collection.trigger("selected", this.model);
      //      this.render();
    }

  });

  var ImagePreview = View.extend({
    template: template,
    
    events: {
      "click .thumbnail": "modalPreview"
    },

    // Flags to be used in template and events handlers.
    flags: {
      check: false,     // This flag will render a check doing this photo checkable.
      progress: false,  // This flag will render a check doing this photo checkable.
      modal: false      // This flag will render a check doing this photo checkable.
    },
    
    initialize: function(options) {
      options || (options = {});
      View.prototype.initialize.call(this, options);

      if(options.flags) {
        // Set the flags from the options
        this.flags = options.flags;
      }
    },

    render: function() {
      View.prototype.render.call(this);
      if(this.flags.check) {
        var checkView = new CheckView({model: this.model});
        this.$(".input-append", this.el).append(checkView.render().el);
      }
      
      return this;
    },

    modalPreview: function() {
      if(this.flags.modal) {
        console.log("Modal preview calling");
        var position = this.collection.indexOf(this.model);
        if(position >= this.collection.pagination.getLimit()) {
            position -= this.collection.pagination.getLimit(); // When whe change the page the position of the models into the pagination would be different.
        }
        var modal = new PhotoAlbumModal({models: this.collection.pagination.models(), position: position});
        modal.render();
      }
    },

    getRenderData: function() {
      var data = View.prototype.getRenderData.call(this);
      data._flags = this.flags;
      console.log("--------- testing ---------------");
      console.log(data);
      console.log("------------------------");
      return data;
    }
    
  });

  return ImagePreview;
});